standard.controller('ContactCtrl', function($scope, $filter, $resource, restfull) {

	restfull.query('/standard/orglist', {}, function(resp) {
		$scope.groups = [];
		angular.forEach(resp.datas.orglist, function(item, n) {
			$scope.groups[n] = {name : item.orgName};
		});
    });
		
    restfull.query('/standard/contacts', {}, function(resp) {
    	$scope.items = resp.datas.userlist;
		$scope.item = $filter('orderBy')($scope.items,'name')[0];
		$scope.item.selected = true;
    });

	$scope.filter = '';
	$scope.selectGroup = function(item) {
		angular.forEach($scope.groups, function(item) {
			item.selected = false;
		});
		angular.forEach($scope.items, function(item) {
			item.selected = false;
		});
		$scope.group = item;
		$scope.group.selected = true;
		$scope.filter = item.name; //通过filter:{group:filter}启用过滤
		var visibleitem = $filter('filter')($scope.items, {group:$scope.filter});
		visibleitem = $filter('filter')(visibleitem, $scope.query);
		$scope.item = $filter('orderBy')(visibleitem,'name')[0];	
		$scope.item.selected = true;
	};

	$scope.createGroup = function() {
		var group = { name : '新增组织部门' };
		group.name = $scope.checkItem(group, $scope.groups, 'name');
		$scope.groups.push(group);
	};

	$scope.checkItem = function(obj, arr, key) {
		var i = 0;
		angular.forEach(arr, function(item) {
			if (item[key].indexOf(obj[key]) == 0) {
				var j = item[key].replace(obj[key], '').trim();
				if (j) {
					i = Math.max(i, parseInt(j) + 1);
				} else {
					i = 1;
				}
			}
		});
		return obj[key] + (i ? ' ' + i : '');
	};

	$scope.deleteGroup = function(item) {
		$scope.groups.splice($scope.groups.indexOf(item), 1);
	};

	$scope.editItem = function(item) {
		if (item && item.selected) {
			item.editing = true;
		}
	};
	
	$scope.doneEditing = function(item) {
		item.editing = false;
		if(item.name != undefined && item.name != '' && item.mobile != undefined && item.mobile != ''){
			$resource(encodeURL('/standard/contacts/save'), item).get(function(resp) {});
		}
	};
	
	$scope.selectItem = function(item) {
		angular.forEach($scope.items, function(item) {
			item.selected = false;
			item.editing = false; //解除右侧编辑界面的状态
		});
		$scope.item = item;
		$scope.item.selected = true;
	};

	$scope.deleteItem = function(item) {
		$scope.items.splice($scope.items.indexOf(item), 1);
		$resource(encodeURL('/standard/contacts/del'), item).get(function(resp) {});
		var visibleitem = $filter('filter')($scope.items, {group:$scope.filter});
		visibleitem = $filter('filter')(visibleitem, $scope.query);
		$scope.item = $filter('orderBy')(visibleitem,'name')[0];	
		if ($scope.item) $scope.item.selected = true;
	};

	$scope.createItem = function() {
		var item = {};
		$scope.items.push(item);
		$scope.selectItem(item);
		$scope.item.editing = true;
	};
});